package com.e2oto.seller.modules.seller.presenter;

import android.os.Environment;

import com.alibaba.fastjson.JSONObject;
import com.e2oto.seller.common.EasyAES;
import com.e2oto.seller.common.base.BaseBean;
import com.e2oto.seller.common.base.BasePresenter;
import com.e2oto.seller.common.base.LoadingDialog;
import com.e2oto.seller.common.http.ProgressSubscriber;
import com.e2oto.seller.common.http.ProgressSubscriberOnNextListener;
import com.e2oto.seller.common.utils.ImageCompressUtils;
import com.e2oto.seller.common.utils.RetrofitUtils;
import com.e2oto.seller.common.utils.SPtools;
import com.e2oto.seller.modules.SellerApp;
import com.e2oto.seller.modules.seller.bean.AddGoodsFirstStepResultBean;
import com.e2oto.seller.modules.seller.bean.FirstSystemCategoryBean;
import com.e2oto.seller.modules.seller.dto.AddGoodsAllCategoryBean;
import com.e2oto.seller.modules.seller.views.AddGoodsBaseInfoView;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

/**
 * Created by ZhangLiQiang on 2017/11/13.
 */

public class AddGoodsBaseInfoPresenter extends BasePresenter<AddGoodsBaseInfoView> {

    /***
     * 添加商品第一步
     * @param category_ids
     * @param goods_name
     * @param keywords
     * @param old_price
     * @param images
     */
    public void addGoodsFirstStep(List<Integer> category_ids, String goods_name, String keywords, String old_price, List<String> images) {

        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < category_ids.size(); i++) {
            sb.append(category_ids.get(i) + ",");
        }

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("seller_id", SellerApp.sellerId);
        jsonObject.put("category_ids", sb.toString());
        jsonObject.put("goods_name", goods_name);
        jsonObject.put("keywords", keywords);
        jsonObject.put("old_price", old_price);

        MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM)
                .addFormDataPart("param", EasyAES.encrypt(jsonObject))
                .addFormDataPart("ver", SellerApp.versionName);
        List<File> compressedImages;
        try {
            compressedImages = ImageCompressUtils.getCompressedImageList(images, getContext());
        } catch (Exception e) {
            e.printStackTrace();
            getView().showMessage(e.toString());
            return;
        }
        for (int i = 0; i < compressedImages.size(); i++) {
            File file = compressedImages.get(i);
            builder.addFormDataPart("img_" + i, file.getName(), RequestBody.create(MediaType.parse("image/jpeg"), file));
        }

        RetrofitUtils.getApiService().addGoodsFirstStep(builder.build())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new ProgressSubscriber<>(new ProgressSubscriberOnNextListener<AddGoodsFirstStepResultBean>() {
                    @Override
                    public void onNext(AddGoodsFirstStepResultBean bean) {
                        getView().addFirstStepCallback(bean);
                    }
                }, getContext()));

    }

    /**
     * @param is_batch 是否批发[1:是;0:不是]
     */
    public void getCategory(int is_batch) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("seller_id", SellerApp.sellerId);
        if (is_batch == 0) {
            jsonObject.put("category_id", SPtools.getInteger(getContext(), "category_id", -1));
        } else {
            jsonObject.put("category_id", SPtools.getInteger(getContext(), "batch_category_id", -1));
        }
        jsonObject.put("is_batch", is_batch);

        RetrofitUtils.getApiService().getCategorySecond(EasyAES.encrypt(jsonObject), SellerApp.versionName)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new ProgressSubscriber(new ProgressSubscriberOnNextListener<AddGoodsAllCategoryBean>() {
                    @Override
                    public void onNext(AddGoodsAllCategoryBean bean) {
                        getView().getCategoryCallback(bean);
                    }
                }, getContext()));


    }

    /***
     *
     * @param category_ids
     * @param goods_name
     * @param keywords
     * @param old_price
     * @param images images里面包含老图(http开头)和新图(本地地址开头)
     */
    public void updateGoodsInfo(int goodsId, List<Integer> category_ids, String goods_name, String keywords, String old_price, List<String> images) {

        final LoadingDialog loadingDialog = new LoadingDialog(getContext());

        List<String> oldImages = new ArrayList<>();// Environment.getExternalStorageDirectory()开头
        List<String> newImages = new ArrayList<>();//http 开头
        for (int i = 0; i < images.size(); i++) {
            String path = images.get(i);
            if (images.get(i).startsWith("http")) {
                oldImages.add(path);
            } else {
                newImages.add(path);
            }
        }


        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < category_ids.size(); i++) {
            sb.append(category_ids.get(i) + ",");
        }

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("goods_id", goodsId);
        jsonObject.put("seller_id", SellerApp.sellerId);
        jsonObject.put("category_ids", sb.toString());
        jsonObject.put("goods_name", goods_name);
        jsonObject.put("keywords", keywords);
        jsonObject.put("old_price", old_price);
        jsonObject.put("old_cover", oldImages.toArray());
        String param = EasyAES.encrypt(jsonObject);
        MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM)
                .addFormDataPart("param", param)
                .addFormDataPart("ver", SellerApp.versionName);
        List<File> compressedImages;//装的new added image
        try {
            compressedImages = ImageCompressUtils.getCompressedImageList(newImages, getContext());
        } catch (Exception e) {
            e.printStackTrace();
            getView().showMessage(e.toString());
            return;
        }
        for (int i = 0; i < compressedImages.size(); i++) {
            File file = compressedImages.get(i);
            builder.addFormDataPart("img_" + i, file.getName(), RequestBody.create(MediaType.parse("image/jpeg"), file));
        }


        RetrofitUtils.getApiService().updateGoodsInfo(builder.build())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<BaseBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        loadingDialog.show();
                    }

                    @Override
                    public void onNext(BaseBean baseBean) {
                        if (baseBean.getCode() == 200) {
                            getView().updateGoodsCallback(baseBean.getMsg());
                        } else {
                            getView().showMessage(baseBean.getMsg());
                        }

                    }

                    @Override
                    public void onError(Throwable e) {
                        loadingDialog.dismiss();
                        getView().showMessage(e.toString());
                    }

                    @Override
                    public void onComplete() {
                        loadingDialog.dismiss();
                    }
                });


    }

}
